package com.fsg.user.provider;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fsg.common.request.user.ReqUser;
import com.fsg.common.response.ResultBean;
import com.fsg.user.entity.User;
import com.fsg.user.service.UserService;
import com.fsg.user.util.RedisUtil;

@RestController
public class SsoController {

	@Autowired
	RedisUtil redisUtil;

	@Autowired
	UserService userService;
	
	/**
     * 判断key是否存在
     */
    @RequestMapping("/redis/hasKey/{key}")
    public Boolean hasKey(@PathVariable("key") String key) {
        try {
            return redisUtil.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
	
    @RequestMapping("/sso/checkUsernameAndPassword")
    private String checkUsernameAndPassword(String username, String password) {
        //通行令牌
        String flag = null;
        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
		queryWrapper.eq("name", username);
		queryWrapper.eq("password", password);
		User findUser = userService.getOne(queryWrapper);
        if(!ObjectUtils.isEmpty(findUser)) {
            //用户名+时间戳（这里只是demo，正常项目的令牌应该要更为复杂）
            flag = username + System.currentTimeMillis();
           // redisUtil.set(flag, 1, 60*3);
        }
        
        return flag;
    }

    /**
     * 跳转登录页面
     */
    @RequestMapping("/sso/loginPage")
    private ModelAndView loginPage(String url) {
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("url", url);
        return modelAndView;
    }

    /**
     * 页面登录
     */
    @RequestMapping("/sso/login")
    private ModelAndView login(HttpServletResponse response, ReqUser requser) {
        String check = checkUsernameAndPassword(requser.getName(), requser.getPassword());
        if (!StringUtils.isEmpty(check)) {
            try {
                Cookie cookie = new Cookie("accessToken", check);
                cookie.setMaxAge(60 * 3);
                //设置域
//                cookie.setDomain("huanzi.cn");
                //设置访问路径
                cookie.setPath("/");
                response.addCookie(cookie);
                //重定向到原先访问的页面
                response.sendRedirect(requser.getUrl());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("main?url="+requser.getUrl());
        modelAndView.addObject("error", "用户名或密码错误");
        return modelAndView;
    }
}
